from flask import Flask, render_template, request, redirect, url_for
import pymysql
import datetime

app = Flask(__name__, template_folder='')

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': 'sunyanwen',
    'database': 'diarydb'
}

# 连接数据库并执行查询的函数
def execute_query(query, params=()):
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute(query, params)
            connection.commit()
            result = cursor.fetchall()
            return result
    finally:
        connection.close()

# 主页路由，显示历史记录
@app.route('/')
def index():
    entries = execute_query("SELECT * FROM entries ORDER BY date DESC")
    return render_template('index.html', entries=entries)

# 提交日记的路由
@app.route('/submit', methods=['POST'])
def submit():
    date = datetime.datetime.now().date()
    weather = request.form['weather']
    mood = request.form['mood']
    events = request.form['events']
    query = "INSERT INTO entries (date, weather, mood, events) VALUES (%s, %s, %s, %s)"
    execute_query(query, (date, weather, mood, events))
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)